#include <WProgram.h>
#include <stdlib.h>
#include <limits.h>
#include "printbuf.h"

//#define DEBUG
#include "debug.h"

extern void adbWrite(uint8_t* data, uint16_t len);

PrintBuf* PrintBuf::loneSingleton = NULL;
PrintBuf::PrintBuf() : useADB(false), 
		       index(0),
		       overflow(false)
{
  loneSingleton = this;
}

void PrintBuf::clear()
{
  index = 0;
  overflow = false;
}

void PrintBuf::add(uint8_t c,char sep)
{
  char cf[4];
  snprintf(cf,sizeof(cf),"%d", (int)c);
  add(cf,sep);
}

void PrintBuf::add(uint16_t c,char sep)
{
  char cf[6];
  snprintf(cf,sizeof(cf),"%d",(int)c);
  add(cf,sep);
}

void PrintBuf::add(const char* str, char sep)
{
  int len = strlen(str);
  if (index+len+1 > sizeof(buf)) {
    overflow = true;
    return;
  }

  strcpy(buf+index,str);
  index += len;
  buf[index++] = sep;
}

boolean PrintBuf::printAdb()
{
  adbWrite((uint8_t*)buf,index);
  return true;
}

void PrintBuf::printSerial()
{
  if (overflow) {
    _DPRINT("Overflowed!");
  }
  for (int i=0;i<index;i++) {
    Serial.print(buf[i]);
  }
}

boolean PrintBuf::print()
{
  boolean ret;
  if (useADB) {
    ret = printAdb();
    // printSerial();
  } else {
    printSerial();
    ret = true;
  }
  clear();
  return ret;
}


